<template>
		 <div class="shop-order--detail" >
			 <block v-if="showPage">
		      <div class="title">
		        <div>订单详情</div>
		        <div class="red" v-if="data.state == 1 || data.state == 2">待付款</div>
		        <div class="grey" v-if="data.state == 0">已取消</div>
		        <div class="yellow" v-if="data.state == 3">待发货</div>
		        <div class="blue" v-if="data.state == 4">待收货</div>
		        <div class="green" v-if="data.state == 5 || data.state == 6">
		          交易成功
		        </div>
		      </div>
		      <div class="pay-down" v-if="data.state == 1 || data.state == 2">
		          <u-count-down @end="handleFinish" font-size="40" :timestamp="timeStamp" format="HH:mm:ss"></u-count-down>
		        <div>请在倒计时结束之前完成支付</div>
		      </div>
		      <div class="pay-address" v-if="data">
		        <div class="address-userinfo">
		          <image class="address-userinfo--icon" src="../../static/shop/pay/address.png" />
		          <div class="address-userinfo--name">{{ data.connector }}</div>
		          <div class="address-userinfo--tel">{{ data.phone }}</div>
		        </div>
		        <div class="address-detail">
		          <div>
		            {{ data.province }}/{{ data.city }}/{{ data.region }}
		            <br />
		            {{ data.address }}
		          </div>
		          <div>
		            <van-icon name="arrow" size="5vw" />
		          </div>
		        </div>
		      </div>
		      <div class="pay-shopping">
		        <div class="shopping-title">
		          <div></div>
		          共{{ data.orderList.length }}件商品
		        </div>
		        <div
		          class="shopping-shop"
		          v-for="(item, index) in data.orderList"
		          :key="index"
		          @click="gotoShop(item)"
		        >
		          <div class="shopping-shop--img">
		            <van-image
		              width="100"
		              height="100"
		              lazy-load
		              :src="item.model.img"
		              fit="cover"
		              r
		            />
		          </div>
		          <div class="shopping-shop--text">
		            <div>{{ item.wares.name }}</div>
		            <div>
		              {{ item.model.specificationsValue.replace(/"|{|}/g, "") }}
		            </div>
		            <div>
		              <div>￥{{ item.price }}</div>
		              <div>x{{ item.count }}</div>
		            </div>
		          </div>
		        </div>
		        <div class="total-cost">
		          <div>商品总价</div>
		          <div><span>￥</span>{{ Number(data.waresAmount).toFixed(2) }}</div>
		        </div>
				<div class="total-cost">
				  <div>配送方式(普通配送)</div>
				  <div><span>￥</span>{{ Number(data.freight).toFixed(2) }}</div>
				</div>
		        <div
		          class="discount-cost"
		          v-if="
		            !((data.totalAmount - data.needPay).toFixed(2) == 0) &&
		            data.state !== 0
		          "
		        >
		          <div>优惠</div>
		          <div>- ￥{{ (data.totalAmount - data.needPay).toFixed(2) }}</div>
		        </div>
		        <div class="need-pay" v-if="data.state !== 0">
		          <div v-if="data.state == 1 || data.state == 2">待付款</div>
		          <div v-else>已付款</div>
		          <div><span>￥</span>{{ Number(data.needPay).toFixed(2) }}</div>
		        </div>
		      </div>
		      <div class="order-no">
		        <div class="order-title">
		          <div></div>
		          <span>订单号</span>{{ data.orderNum }}
		        </div>
		        <div class="space" style="margin: 15px"></div>
		        <div class="time">
		          <span>支付方式：</span
		          >{{ data.payment === 0 ? "线下支付" : "微信支付" }}
		        </div>
		        <div class="time"><span>下单时间：</span>{{ data.createTime }}</div>
		        <div class="time" v-if="data.pay && data.state > 2">
		          <span>付款时间：</span
		          >{{ data.pay.payConfirmTime ? data.pay.payConfirmTime : "等待确认" }}
		        </div>
		        <div class="time" v-if="data.deliveTime">
		          <span>发货时间：</span>{{ data.deliveTime }}
		        </div>
		        <div class="time" v-if="data.receiveTime">
		          <span>成交时间：</span>{{ data.receiveTime }}
		        </div>
		      </div>
		      <div class="btn-footer">
		        <view
		          type="default"
		          class="ghost"
		          v-if="data.state == 3"
		          @click="editAdd"
		          >修改地址</view
		        >
		        <view
		          type="default"
		          :class="disMore ? 'gray-blue' : 'ghost'"
		          @click="goPay"
		          >再来一单</view
		        >
		        <view type="default" class="ghost" @click="call"
		          >联系售后</view
		        >
		        <view
		          type="default"
		          class="ghost"
		          v-if="data.state == 1 || data.state == 2"
		          @click="cancelOrder"
		          >取消订单</view
		        >
		        <view
		          type="default"
		          class="ghost"
		          v-if="data.state == 4"
		          @click="gotoLogistics"
		          >查看物流</view
		        >
		        <view
		          type="default"
		          class="blue"
		          v-if="data.state == 1 || data.state == 2"
		          @click="pay"
		          >立即付款</view
		        >
		        <view
		          type="default"
		          class="blue"
		          v-if="data.state == 3"
		          @click="tips"
		          >提醒发货</view
		        >
		        <view
		          type="default"
		          class="blue"
		          v-if="data.state == 4"
		          @click="confirm"
		          >确认收货</view
		        >
		        <view
		          type="default"
		          class="blue"
		          v-if="data.state == 5"
		          @click="openEvaluate"
		          >我要评价</view
		        >
		      </div>

		      <!-- 评价 -->
		      <van-popup @close="onClose" safe-area-inset-bottom :show="showEvaluate" custom-style="max-height:80vh;min-height:50vh;" round  position="bottom">
		      		  <div
		      		        style="
		      		          height: 8vh;
		      		          display: flex;
		      		          align-items: center;
		      		          font-weight: bold;
		      		          justify-content: space-between;
		      		        "
		      		      >
		      		        <div
		      		          style="color: #e15a3b; margin-left: 16px; font-size: 4.3vw"
		      		          @click="showEvaluate = false"
		      		        >
		      		          取消
		      		        </div>
		      		        <div style="font-size: 4.8vw">评价</div>
		      		        <div
		      		          style="color: #5a9bef; margin-right: 16px; font-size: 4.3vw"
		      		          @click="submitEvalute"
		      		        >
		      		          确定
		      		        </div>
		      		      </div>
		      			  <van-field
		      			    clearable
		      			    :value="message"
		      				@input="handleInput"
		      			    rows="5"
		      			    autosize
		      			    type="textarea"
		      			    maxlength="100"
		      			    placeholder="写下您对商品的评价吧（不超过100字）"
		      			    show-word-limit
		      			  />
		      		      <div
		      		        style="
		      		          font-size: 4vw;
		      		          color: #888888;
		      		          padding: 0 16px 0 16px;
		      		          display: flex;
		      		          justify-content: space-between;
		      		        "
		      		      >
		      		        <div>{{ evaluateTime }}</div>
		      		      </div>
		      		      <van-divider :style="{ color: '#F2F2F2', }" />
		      		        <div style="font-size: 4vw; font-weight: bold;margin-left: 32rpx;">星级评价</div>
		      				<view class="rate-div"><u-rate :size="60" :gutter="50" :count="5" v-model="evaluateValue"></u-rate></view>
		      </van-popup>
			  </block>
		</div>
</template>

<script>
	import api from '../../untils/api.js'
	export default {
		data() {
			return {
				data:{},
				timeStamp:"",
				id:"",
				disMore:false,
				showEvaluate:false,
				evaluateData:{},
				evaluateTime:"",
				message:"",
				evaluateValue:0,
				showPage:false,
				timer:null,
			}
		},
		methods: {
			handleInput(e){
				this.message=e.detail
			},
			gotoLogistics(){
				console.log("sdw")
				uni.navigateTo({
					url:`../logistics/logistics?id=${this.id}&orderNum=${this.data.orderNum}`
				})
			},
		    async pay(){
				if(this.data.payment === 0){
					 await api.SM_ORDER_PAYMENT(JSON.stringify({id:this.id,payment:0}))
				}
				else {
					var that=this
					var obj={};
					obj.id=this.id;
					obj.clientType=2;
					obj.modelInfo=[];
					var modelObj={};
					this.data.orderList.forEach((item)=>{
										 modelObj.id=item.model.id
										 modelObj.count=item.count
										 obj.modelInfo.push(modelObj)
					});
					api.WX_CREATE_SM_PAY(JSON.stringify(obj)).then((res)=>{
										   wx.requestPayment({
										     timeStamp: res.data.body.timeStamp,
										     nonceStr: res.data.body.nonceStr,
										     package: res.data.body.packageValue,
										     signType: 'MD5',
										     paySign: res.data.body.paySign,
										     success: (res)=>{ 
												 that.init();
											 },
										     fail: async (res)=> { 
												 await api.SM_PAY_CANCEL(JSON.stringify(that.id));
												 that.init();
												},
											 // cancel: async (res)=> { 
												//   console.log("dagfsdg")
												//  await api.SM_PAY_CANCEL(JSON.stringify(that.orderId));
												//  uni.redirectTo({
												//    url: `../orderDetail/orderDetail?id=${that.orderId}`
												//  })
												// },
										   })
					})
				}
			},
			// 提交评论
			    async submitEvalute() {
			      if (this.message === "") {
			       uni.showToast({
			       	title: "请填写评论！",
			       	icon:'none',
			       	duration:1000
			       });
			        return;
			      }
			      if (this.evaluateValue === 0) {
					  uni.showToast({
					  	title: "请选择评分星级！",
					  	icon:'none',
					  	duration:1000
					  });
			        return;
			      }
			      try {
			        let evaluateList = [];
			        await this.evaluateData.orderList.map((item) => {
			          evaluateList.push({
			            smOrder: { id: this.evaluateData.id },
			            wares: { id: item.wares.id },
			            content: this.message,
			            logisticsScore: this.evaluateValue,
			            waresScore: this.evaluateValue,
			            salerScore: this.evaluateValue,
			            model: { id: item.model.id },
			          });
			        });
			        await api.SM_EVALUATE_LIST_SAVE( JSON.stringify(evaluateList) );
			      } finally {
			        this.message = "";
			        this.evaluateValue = 0;
			        this.showEvaluate = false;
					uni.showToast({
						title: "评价成功！",
						icon:'none',
						duration:1000
					});
					this.init();
			      }
			    },
			onClose(){
				this.showEvaluate=false
			},
			openEvaluate(){
				this.showEvaluate=true
				this.evaluateData = this.data;
				this.evaluateTime=this.$u.timeFormat(new Date().getTime(), 'yyyy-mm-dd hh:MM:ss');
			},
			// 确认收货
			    confirm() {
					var that=this
			      uni.showModal({
					  content: '是否确认收货？',
					  success (res) {
					      if (res.confirm) {
					        api.SM_ORDER_CONFIRM(JSON.stringify({id:that.data.id})).then((res)=>{
								if(res.data.header.result_code==0){
									uni.showToast({
										icon:"success",
										title:"收货成功",
										duration:2000
									})
									that.init();
								}
							})
					      } else if (res.cancel) {
					        console.log('用户点击取消')
					      }
					    }
			        })
			 },
			cancelOrder() {
			    uni.navigateTo({
			    	url: `../cancleOrder/cancleOrder?orderId=${this.data.id}&needPay=${this.data.needPay}`
			    })
			},
			tips() {
							 uni.showToast({
							 	title: "提醒发货成功，请耐心等待！",
							 	icon:'none',
							 	duration:1000
							 });
			 },
			// 再来一单
			 goPay() {
				   this.data.orderList.map((item) => {
			         if (item.wares.state !== 1) {
			           this.disMore = true;
						uni.showToast({
										title: "该订单中有商品已下架，无法生成订单！",
										icon:'none',
										duration:2000
						});
				      throw new Error();
			         }
					 if (!item.model.stock||item.count>item.model.stock) {
					   this.disMore = true;
					 	uni.showToast({
					 							title: "该订单中有商品库存不足，无法生成订单！",
					 							icon:'none',
					 							duration:3000
					 						});
					 	throw new Error();
					 }
					 if (item.model.buyLimit!==0&&item.count>item.model.buyLimit) {
					     this.disMore = true;
					 	uni.showToast({
					 							title: "该订单中有商品购买数量超标，无法生成订单！",
					 							icon:'none',
					 							duration:3000
					 						});
					 	throw new Error();
					 }
					});
					var list=[]
					this.data.orderList.forEach((item)=>{
										  var obj={};
										  console.log(item)
										  obj.price=item.price;
										  obj.img=item.img;
										  obj.stock=item.stock;
										  obj.id=item.id;
										  obj.specificationsValue=item.specificationsValue;
										  obj.wares=item.wares;
										  obj.model=item.model;
										  obj.count=item.count;
										  list.push(obj)
					})
					uni.navigateTo({
						url:`../confirmOrder/confirmOrder?list=${JSON.stringify(list)}&orderFrom=2`
					})
			   },
			 editAdd() {
	            uni.navigateTo({
	            	url:`../address/address?orderId=${this.id}`
	            })
			 },
			 // 跳转到商品详情
			     gotoShop(item) {
					 if (item.wares.state !== 1) {
					 		uni.showToast({
					 										title: "商品已下架！",
					 										icon:'none',
					 										duration:2000
					 		});
					 }
					 else {
						uni.navigateTo({
							url:`../detail/detail?id=${item.wares.id}`
						}) 
					 }
			     },
			call(){
				console.log("afsg")
				uni.makePhoneCall({
				    phoneNumber: '4006669918' 
				})
			},
			handleFinish(){
				this.init();
			},
		  async	init(){
				this.showPage=false;
				uni.showLoading({
					title:"加载中"
				});
			  await	api.SM_ORDER_SELECT_BY_PRIMARYKEY(JSON.stringify(this.id)).then((res)=>{
						this.data=res.data.body
						this.timeStamp= (new Date(this.data.payEndTime.replace(/-/g, "/")).getTime() - new Date().getTime())/1000;
					})
				this.showPage=true;
				uni.hideLoading();
			},
		},
		onLoad(e) {
			this.id=e.id
		    this.timer=setInterval(()=>{
				api.SM_ORDER_SELECT_BY_PRIMARYKEY(JSON.stringify(this.id)).then((res)=>{
				 this.data=res.data.body
			     this.timeStamp= (new Date(this.data.payEndTime.replace(/-/g, "/")).getTime() - new Date().getTime())/1000;
				})
			},5000);
		},
		onUnload() {
			clearInterval(this.timer);
		},
		onShow() {
			this.init();
		}
	}
</script>

<style lang='scss' scoped>
	.rate-div{
		width: 100vw;
		display: flex;
		flex-direction: row;
		justify-content: center;
		margin-top: 50rpx;
	}
.shop-order--detail {
  padding: 5vw 5vw 60px 5vw;
  background: #f5f7f9;
  min-height: 100vh;
  color: #434343;
  font-size: 5vw;
  font-weight: bold;
  .title {
    display: flex;
    justify-content: space-between;
    & > div:last-child {
      font-size: 4.2vw;
    }
  }
  .green {
    color: #3fae43;
  }
  .blue {
    color: #3b8aed;
  }
  .yellow {
    color: #e1ac3b;
  }
  .red {
    color: #e15a3b;
  }
  .pay-down {
    background: #fff;
    margin-top: 4vw;
    box-shadow: 1px 1px 24px 0px rgba(79, 93, 117, 0.08);
    border-radius: 3vw;
    padding: 4vw;
    text-align: center;
    div {
      font-size: 3.4vw;
      margin-left: 3vw;
    }
  }
  .pay-address {
    background: #fff;
    margin-top: 4vw;
    box-shadow: 1px 1px 24px 0px rgba(79, 93, 117, 0.08);
    border-radius: 3vw;
    padding: 4vw 4vw 7vw 4vw;
    .address-userinfo {
      display: flex;
      align-items: flex-end;
      div {
        margin-right: 2.5vw;
      }
      .address-userinfo--icon {
        width: 5vw;
        height: 5vw;
        margin-bottom: 1.6px;
		margin-right: 2vw;
      }
      .address-userinfo--name {
        color: #343434;
        font-size: 4.5vw;
        font-weight: bold;
      }
      .address-userinfo--tel {
        color: #9a9a9a;
        font-size: 3.6vw;
        font-weight: bold;
      }
    }
    .address-detail {
      color: #343434;
      font-size: 4.2vw;
      font-weight: 600;
      margin-top: 4vw;
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-left: 7.5vw;
      line-height: 7vw;
      div:last-child {
        color: #c8c8cc;
      }
    }
  }
  .pay-shopping {
    margin-top: 3vw;
    background: #fff;
    padding: 4vw 4vw 4vw 4vw;
    border-radius: 3vw;
    box-shadow: 1px 1px 24px 0px rgba(79, 93, 117, 0.08);
    color: #343434;
    .shopping-title {
      font-size: 4.2vw;
      font-weight: bold;
      display: flex;
      div {
        background: url("../../static/shop/pay/shop.png");
        width: 5vw;
        height: 5vw;
        background-size: 100%;
        margin-right: 2vw;
      }
    }
  }
  .shopping-shop {
    margin-top: 8vw;
    display: flex;
    .shopping-shop--img {
      height: 30vw;
      width: 30vw;
      .van-image {
        border-radius: 3vw;
      }
    }
    .shopping-shop--text {
      width: 52vw;
      & > div:first-child {
        font-size: 4vw;
      }
      & > div:nth-child(2) {
        font-size: 3.9vw;
        color: #9a9a9a;
        margin: 5vw 0 5vw 0;
      }
      & > div:nth-child(3) {
        display: flex;
        justify-content: space-between;
        align-items: flex-end;
        div:first-child {
          color: #cc363c;
          font-size: 5vw;
        }
        div:last-child {
          font-size: 4.8vw;
        }
      }
    }
  }
  .pay-address:active {
    background: #f2f3f5;
  }
}

.total-cost {
  margin-top: 3vw;
  font-size: 4vw;
  color: #999999;
  display: flex;
  justify-content: space-between;
  div {
    span {
      font-size: 3vw;
    }
  }
}

.discount-cost {
  margin-top: 3vw;
  font-size: 4vw;
  color: #333;
  display: flex;
  justify-content: space-between;
  div:last-child {
    color: #cc363c;
  }
}

.need-pay {
  display: flex;
  font-size: 4vw;
  margin-top: 3vw;
  justify-content: space-between;
  & > div:last-child {
    color: #cc363c;
    span {
      font-size: 3vw;
    }
  }
}

.order-no {
  margin-top: 3vw;
  background: #fff;
  padding: 4vw 4vw 7vw 4vw;
  border-radius: 3vw;
  box-shadow: 1px 1px 24px 0px rgba(79, 93, 117, 0.08);
  color: #343434;
  .order-title {
    font-size: 4.2vw;
    font-weight: bold;
    display: flex;
    align-items: center;
    div {
      background: url("../../static/shop/order.png");
      width: 5vw;
      height: 5vw;
      background-size: 85% 100%;
      background-repeat: no-repeat;
      margin-right: 2vw;
    }
    span {
      margin-right: 2vw;
    }
  }
  .time {
    font-size: 4vw;
    padding: 2vw;
    span {
      color: #999999;
    }
  }
}

.btn-footer {
  height: 12vw;
  width: 100%;
  background: #fff;
  position: fixed;
  bottom: 0;
  left: 0;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  padding: 0 6px 0 6px;
  line-height: 8vw;
  text-align: center;
  .ghost {
    width: 20vw;
    height: 8vw;
    border: 1px solid #74a9f0;
    border-radius: 17px;
    color: #3b8aed;
    font-size: 2.8vw;
    white-space: nowrap;
	margin-right: 20rpx;
  }
  .blue {
    width: 20vw;
    height: 8vw;
    border-radius: 17px;
    color: #fff;
    font-size: 2.8vw;
    background: #509afe;
    white-space: nowrap;
	margin-right: 20rpx;
  }
  .blue-ghost {
    color: #3b8aed;
    background: #fff;
    border: 1px solid #3b8aed;
    border-radius: 1.8vw;
    width: 2vw;
    height: 8vw;
    font-size: 2.8vw;
    white-space: nowrap;
	margin-right: 20rpx;
  }
  .gray-blue {
    width: 20vw;
    height: 8vw;
    border: 1px solid #b9cfeb;
    border-radius: 17px;
    color: #b9cfeb;
    font-size: 2.8vw;
    white-space: nowrap;
	margin-right: 20rpx;
  }
}
</style>
